package com.wang.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.auth.mapper.SysRoleMapper;
import com.wang.auth.service.SysRoleService;
import com.wang.auth.service.SysUserRoleService;
import com.wang.model.system.SysRole;
import com.wang.model.system.SysUserRole;
import com.wang.model.system.vo.AssignRoleVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author wang
 * @since 2023-04-17
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Resource
    SysUserRoleService userRoleService;

    @Override
    public Map<String, Object> findRoleDataByUserId(Long userId) {
        //查询所有角色信息
        List<SysRole> allSysRoleList = this.list();
        //查询当前用户的角色信息
        List<SysRole> sysRoleList = baseMapper.selectSysRoleJoinSysUserRole(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("assginRoleList",sysRoleList);
        map.put("allRolesList",allSysRoleList);
        return map;
    }

    @Override
    public void doAssign(AssignRoleVo assignRoleVo) {
        LambdaQueryWrapper<SysUserRole> sysUserRoleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysUserRoleLambdaQueryWrapper.eq(assignRoleVo.getUserId() != null,SysUserRole::getUserId,assignRoleVo.getUserId());
        boolean remove = userRoleService.remove(sysUserRoleLambdaQueryWrapper);
        List<Long> roleIdList = assignRoleVo.getRoleIdList();
        ArrayList<SysUserRole> sysUserRoles = new ArrayList<>(roleIdList.size());
        for (Long roleId : roleIdList) {
            if (roleId != null){
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(roleId);
                sysUserRole.setUserId(assignRoleVo.getUserId());
                sysUserRoles.add(sysUserRole);
            }
        }
        userRoleService.saveBatch(sysUserRoles);
    }
}
